<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * User_profile
 * @author: Skiychan <dev@skiy.net>
 *
 */

require(APPPATH.'libraries/Android_Controller.php');
class User_profile extends Android_Controller {
    private $_user_info;
    private $_valid_old_phone_code = "_VALID_OLD_PHONE_CODE";

    public function __construct() {
        parent::__construct();
        $services = array(
            'login_service',
            'user_info_service',
            'user_verify_service'
        );
        $this->load->service($services);
        $this->load->library("form_validation");
        $this->config->load("form_validation");
        $this->_user_info = $this->login_service->get_user_info();
    }

    /**
     * 取得用户信息
     */
    public function user_info_get() {
        $this->login_service->reload_user_info();
        $this->_user_info = $this->login_service->get_user_info();
        //空间
        $user_space = array(
            'used_space' => $this->_user_info['used_space'],
            'capacity' => $this->_user_info['capacity']
        );
        $space = $this->user_info_service->get_format_space_info($user_space);

        //手机号及验证
        $mobile = $this->_user_info['n_mobile'];
        $v_mobile = 0;
        if (! empty($this->_user_info['mobile'])) {
            $mobile = $this->_user_info['mobile'];
            $v_mobile = 1;
        }

        //邮箱及验证
        $email = $this->_user_info['n_email'];
        $v_email = 0;
        if (! empty($this->_user_info['email'])) {
            $email = $this->_user_info['email'];
            $v_email = 1;
        }

        $result = array(
            'uid' => $this->_user_info['id'],
            'name' => $this->_user_info['nickname'],
            'company' => $this->_user_info['company_name'],
            'avatar' => $this->user_info_service->fetch_avatar($this->_user_info['image']),
            'mobile' => $mobile,
            'v_mobile' => $v_mobile,
            'email' => $email,
            'v_email' => $v_email,
            'space' => $space
        );

        echo $this->common_response(0, '', array('data' =>$result));
    }

    /**
     * 更新用户信息
     * company  公司名称
     * name     昵称
     */
    public function user_info_put() {
        #修改公司名
        $company = $this->put('company');
        //修改用户名
        $name = $this->put('name');

        //传值
        if ($company !== false) {
            $data['company_name'] = rtrim($company);
        }

        if ($name !== false) {
            $name = rtrim($name);
            if ($name === "") {
                return $this->common_response(1003);
            }
            $data['nickname'] = $name;
        }
        
        if (empty($data))
            return $this->common_response(1003);

        $update = $this->user_info_service->update_user_info($this->_user_info['id'], $data);
        if (!$update)
            return $this->common_response($this->user_info_service);

        #批量修改
        foreach ($data as $key => $value) {
            $this->login_service->refresh_user_info($key, $value);
        }

        return $this->common_response(0);
    }

    /**
     * 退出
     */
    public function logout_get() {
        $client_id = $this->get("client_id");

        if (empty($client_id))
            return $this->common_response(1003);

        //$this->login_service->login_uid = $this->_user_info['id'];
        $add_fast_login = $this->login_service->fast_login_option($client_id,"",2);

        if ($add_fast_login) {
            $this->login_service->logout();
            return $this->common_response(0);
        }

        return $this->common_response($this->login_service);
    }

    /**
     * 更新头像
     */
    public function avatar_post() {
        $update_image = $this->user_info_service->upload_face($this->_user_info['id'],$this->_user_info['image'], 'avatar');
        if ($update_image) {
            $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('image' => $update_image['img']));

            if ($update) {
                $this->login_service->refresh_user_info('image', $update_image['img']);
                $resp = array(
                    'data' => array(
                        'avatar' => $this->user_info_service->fetch_avatar($update_image['img'])
                    )
                );
                return $this->common_response(0, NULL, $resp);
            }
        }

        return $this->common_response($this->user_info_service);
    }

    /**
     * 发送验证码
     * 2首次验证手机 / 3验证旧手机 / 4验证新手机
     * @return
     */
    public function sms_code_post() {
        $this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
        $this->form_validation->set_rules('process', '', 'required');  //进程
        if ($this->form_validation->run() === FALSE)
            $this->common_response(1003);

        $this->load->service("register_service");

        $mobile = trim($this->input->post("mobile", true));
        #手机是否已存在
        $check = $this->register_service->check_phone_exists($mobile);
        $process_type = (int)$this->input->post("process", true);

        #如果不是2,3,4进程则报错
        if (! in_array($process_type, array(2,3,4)))
            return $this->common_response(1003);

        ### 首次验证手机 ###
        if ($process_type == 2) {
            #手机号已经存在,报错
            if ($check)
                return $this->common_response(5009);

            $send = $this->user_verify_service->send_sms($mobile, User_verify_service::PROCESS_VALID_PHONE);
        }

        ### 验证旧手机 ###
        if ($process_type == 3) {
            #旧手机号不存在
            if (! $check)
                return $this->common_response(5004);

            #旧手机
            $old_mobile = $this->login_service->get_user_info('mobile');
            if (empty($old_mobile))
                return $this->common_response(1003);

            $send = $this->user_verify_service->send_sms($old_mobile, User_verify_service::PROCESS_VALID_OLD_PHONE);
        }

        ### 验证新手机 ###
        if ($process_type == 4) {
            #旧手机
            $old_mobile = $this->login_service->get_user_info('mobile');
            #新旧手机相同
            if ($mobile == $old_mobile)
                return $this->common_response(5011);

            #手机号已经存在,报错
            if ($check)
                return $this->common_response(5009);

            $send = $this->user_verify_service->send_sms($mobile, User_verify_service::PROCESS_MODIFY_PHONE);
        }

        if ($send) {
            //更新旧手机验证码
            $this->update_old_mobile_code();
            return $this->common_response(0);
        }

        return $this->common_response($this->user_verify_service);
    }

    /**
     * ::验证邮箱::发送邮箱验证码 account_put 结合使用
     */
    public function email_code_post() {
        $this->form_validation->set_rules('email','', 'required|valid_email');
        if ($this->form_validation->run() === FALSE)
            $this->common_response(1003);

        $email = $this->input->post('email', TRUE);
        $check_user = $this->user_verify_service->check_user_by_email($email);
        if (! $this->login_service->is_login())
            return $this->common_response(1008);

        if ($check_user)
            return $this->common_response(5010);

        //如果已经验证过邮箱则不可再次验证
        $get_email = $this->login_service->get_user_info('email');
        if (! empty($get_email))
            return $this->common_response(5007);

        $send = $this->user_verify_service->send_email($email, User_verify_service::PROCESS_VALID_EMAIL);
        if ($send)
            return $this->common_response(0);

        return $this->common_response($this->user_verify_service);
    }

    /**
     * 验证新建帐号 (手机或邮箱)
     */
    public function account_put() {
        $account = $this->put('account');
        $code = $this->put('code');

        if (! empty($account) || ! empty($code)) {
            $is_mobile = $this->form_validation->valid_mobile_phone($account);
            $is_email = $this->form_validation->valid_email($account);

            if ($is_mobile) {
                $check = $this->user_verify_service->check_sms_code($code, $account, User_verify_service::PROCESS_VALID_PHONE);
                if ($this->check_account_exist($account))
                    return $this->common_response(5011);

            } else if ($is_email) {
                //是否已验证邮箱,APP不可更改邮箱
                if (! empty($this->_user_info['email']))
                    return $this->common_response(5016);

                $check = $this->user_verify_service->check_email_verify_code($code, $account, User_verify_service::PROCESS_VALID_EMAIL);
                //是否和原邮箱相同
                if ($this->check_account_exist($account, 'email'))
                    return $this->common_response(5012);

            } else {
                return $this->common_response(1003);
            }

            if (!$check)
                return $this->common_response($this->user_verify_service);

            if ($is_mobile) {
                $data['mobile'] = $account;
                if (! empty($this->_user_info['n_mobile']))
                    $data['n_mobile'] = '';
            } else {
                $data['email'] = $account;
                if (! empty($this->_user_info['n_email']))
                    $data['n_email'] = '';
            }
            $update = $this->user_info_service->update_user_info($this->_user_info['id'], $data);
            if ($update === FALSE) {
                return $this->common_response($this->user_info_service);
            }
            return $this->common_response(0);
        } else {
            return $this->common_response(1003);
        }
    }

    /**
     * 修改密码
     */
    public function password_put() {
        $old_pwd = trim($this->put('password'));
        $new_pwd = trim($this->put('new_password'));

        if (empty($old_pwd) || empty($new_pwd))
            return $this->common_response(1003);

        if ($old_pwd == $new_pwd)
            return $this->common_response(5017);

        $npwd_valid = $this->form_validation->valid_password($new_pwd);
        if (empty($npwd_valid))
            return $this->common_response(1003);

        #判断旧密码是否正确
        $old_uin = $this->login_service->reload_user_info();
        if (md5($old_pwd) !== $old_uin['password'])
            return $this->common_response(5013);

        $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('password' => md5($new_pwd)));
        if ($update) {
            //$this->login_service->login_uid = $this->_user_info['id'];

            //$this->login_service->fast_login_deprecated();
            return $this->common_response(0);
        }

        return $this->common_response($this->user_info_service);
    }

    /**
     * ::修改手机::验证旧手机的验证码
     */
    public function sms_code_check_post() {
        $this->form_validation->set_rules('code','', 'required');
        if ($this->form_validation->run() === false)
            return $this->common_response(1003);

        $code = trim($this->input->post('code',true));
        $mobile = $this->login_service->get_user_info('mobile');
        if (empty($mobile))
            return $this->common_response(1008);

        $check = $this->user_verify_service->check_sms_code($code, $mobile, User_verify_service::PROCESS_VALID_OLD_PHONE, false);
        if ($check) {
            $this->session->set_userdata($this->_valid_old_phone_code, $code);
            return $this->common_response(0);
        }

        return $this->common_response($this->user_verify_service);
    }

    /**
     * ::修改手机:修改新手机,验证新手机验证码
     */
    public function mobile_new_put() {
        $valid_code = $this->session->userdata($this->_valid_old_phone_code);
        $old_mobile = $this->_user_info['mobile'];

        $mobile = trim($this->put('mobile'));
        $code = trim($this->put('code'));
        if ($old_mobile == $mobile)
            return $this->common_response(5011);

        $mobile_valid = $this->form_validation->valid_mobile_phone($mobile);
        $old_mobile_valid = $this->form_validation->valid_mobile_phone($old_mobile);
        //检测
        if ((! $mobile_valid) || (! $old_mobile_valid) ||
            empty($code) || empty($valid_code)) {
            return $this->common_response(1003);
        }

        $vcheck = $this->user_verify_service->check_sms_code($code, $mobile, User_verify_service::PROCESS_MODIFY_PHONE, true);
        #检测新手机验证码通过
        if ($vcheck) {
            $check = $this->user_verify_service->check_sms_code($valid_code, $old_mobile, User_verify_service::PROCESS_VALID_OLD_PHONE, true);
            #检测旧手机验证码通过
            if ($check) {
                $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('mobile' => $mobile));
                $this->login_service->reload_user_info();
                if ($update) {
                    $this->session->unset_userdata($this->_valid_old_phone_code);
                    return $this->common_response(0);
                }
            }
        }

        return $this->common_response($this->user_verify_service);
    }

    /**
     * 检查输入的新帐号是否与原帐号相同
     * @param $account
     * @param string $type
     * @return bool|void
     */
    private function check_account_exist($account, $type = 'mobile') {
        if (empty($account))
            return $this->common_response(1003);

        if ($type == 'mobile') {
            return $this->_user_info['mobile'] === $account;
        } else if ($type == 'email') {
            return $this->_user_info['email'] === $account;
        }
    }

    /**
     * 为旧手机验证码续期
     * @return mixed
     */
    private function update_old_mobile_code() {
        $code = $this->session->userdata($this->_valid_old_phone_code);
        $mobile = $this->_user_info['mobile'];
        
        $where = array(
            'process'   => 7,
            'receiver'  => $mobile,
            'code'      => $code
        );
        return $this->user_verify_service->renew_verify_code($where);
    }
}
